<template>
  <div>
    <el-select style="display: block;" :size="size" v-model="value" :placeholder="placeholder" @change="changeValue" :disabled="disabled"
               :clearable="clearable" @clear="changeValue">
      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
    </el-select>
  </div>
</template>

<script>
import {getRespData, isNotNull} from "@/util/common-util";
import {getChildList} from "@/api/business/dict";

export default {
  name: "app-dict-select",
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择...'
    },
    dictCode: {
      type: String,
      default: ''
    },
    initValue: {
      type: Object,
      default: null
    },
    size: {
      type: String,
      default: 'small'
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    selectFirst: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [],
      value: ''
    }
  },
  created() {
    this.initOptions(() => {
      if (isNotNull(this.initValue)) {
        this.value = this.initValue
      }
    })
  },
  methods: {
    initOptions(success) {
      this.options = []
      getChildList(this.dictCode).then(res => {
        for (const item of getRespData(res)) {
          this.options.push({
            label: item.dictValue,
            value: item.dictKey
          })
        }
        if (this.selectFirst) {
          this.value = this.options[0].value
          this.changeValue()
        }
        success && success()
      })
    },
    changeValue() {
      this.$emit('change', this.value)
    }
  }
}
</script>
